﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Globalization;

using System.Text.RegularExpressions;
using CommunergyLogic;
using Communergy.Repository;
using Communergy.Repository.EntityFramework;

/// <summary>
/// Summary description for Helpers
/// </summary>
public  static class Helpers
{
    private static Regex isGuid = new Regex(@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$", RegexOptions.Compiled);

    public static bool IsGuid(string candidate, out Guid output)
    {
        bool isValid = false;
        output = Guid.Empty;
        if (candidate != null)
        {
            if (isGuid.IsMatch(candidate))
            {
                output = new Guid(candidate);
                isValid = true;
            }
        }
        return isValid;
    }



    public static string UkDateString(this DateTime DateToDisplay)
    {

        return DateToDisplay.ToString(CultureInfo.CreateSpecificCulture("en-GB").DateTimeFormat.ShortDatePattern);
    }


    public static ElectricityMeter GetMeterIfBelongsToUser(communergyEntities db , string meterIdString)
    {
        ElectricityMeter thisMeter = null;
    
        MembershipUser thisUser = Membership.GetUser();
        
        int meterId;
        if (!string.IsNullOrEmpty(meterIdString))
        {
            if (int.TryParse(meterIdString, out meterId))
            {
                Guid userGuid = new Guid(thisUser.ProviderUserKey.ToString());
                thisMeter = db.ElectricityMeter.Where(m => m.me_id == meterId && m.me_aspUserId == userGuid).FirstOrDefault();
            }
        }
        return thisMeter;
    }



    public static Communergy.Repository.EntityFramework.Group GetGroupIfBelongsToUser(communergyEntities db, string groupIdString)
    {
        Communergy.Repository.EntityFramework.Group thisGroup = null;

        MembershipUser thisUser = Membership.GetUser();

        int groupId;
        if (!string.IsNullOrEmpty(groupIdString))
        {
            if (int.TryParse(groupIdString, out groupId))
            {
                Guid userGuid = new Guid(thisUser.ProviderUserKey.ToString());
                thisGroup = (from gu in db.GroupUser.Include("Group")
                             where gu.Group.gp_id == groupId && gu.gu_userId == userGuid
                             select gu.Group).FirstOrDefault();
            }
        }
        return thisGroup;
    }
}
